// Loading page TypeScript
import { code2session, Code2SessionBody } from '@/miniprogram/utils/apis';
import { WeilaCore, WL_ClientType } from "weilasdk_lite";
import { WeilaMiniNetwork } from "@/miniprogram/utils/weila_mini_network.js";
import { WeilaMiniStorage } from "@/miniprogram/utils/weila_mini_storage.js";

import { TinyEmitter } from "tiny-emitter";
import { register_weila_notification_handler } from '@/miniprogram/utils/util';

Page({
  data: {
    isLoaded: true,
    countdown: 3
  },

  timer: null as any,

  handleSkip(): void {
    if (this.timer) {
      clearInterval(this.timer);
    }
    // 这里添加跳转逻辑
    console.log('跳过广告');
    // 例如跳转到首页
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  startCountdown(): void {
    this.timer = setInterval(() => {
      console.log("start countdown", this.data.countdown);

      this.setData({
        countdown: this.data.countdown - 1
      });
      
      if (this.data.countdown <= 0) {
        if (this.timer) {
          clearInterval(this.timer);
        }
        this.handleSkip();
      }
    }, 1000);
  },

  onLoad(): void {
    (async () => {
      
      getApp<IAppOption>().globalData.weilaCore = new WeilaCore();
      getApp<IAppOption>().globalData.eventEmitter = new TinyEmitter();
      let weilaCore: WeilaCore = getApp<IAppOption>().globalData.weilaCore;
      weilaCore.weila_init(new WeilaMiniNetwork(), new WeilaMiniStorage());
      register_weila_notification_handler(weilaCore, getApp<IAppOption>().globalData.eventEmitter);

      try {
        let res = await wx.login({
          timeout: 10000
        });

        console.log('登录成功', res.code);

        getApp<IAppOption>().globalData.accountInfo = wx.getAccountInfoSync();
        let accountInfo = getApp<IAppOption>().globalData.accountInfo!;
        console.log('获取到的账号信息', accountInfo);

        let rsp = await code2session({
          wx: {
            appid: accountInfo.miniProgram.appId,
          },
          jscode: res.code
        } as Code2SessionBody);

        console.log('获取到的session信息', rsp);

        if (rsp.errcode == 0) {
          getApp<IAppOption>().globalData.openId = rsp.data.wx.openid;
          getApp<IAppOption>().globalData.sessionKey = rsp.data.wx.sessionkey;
          getApp<IAppOption>().globalData.unionid = rsp.data.wx.unionid;

          console.log('获取到的session信息', rsp.data.wx.openid, rsp.data.wx.sessionkey, rsp.data.wx.unionid);
          

          if (rsp.data.account == null) {
            // 没有账号，跳转到登陆界面
            wx.redirectTo({
              url: '/pages/login/login'
            }).then(() => {
              console.log("跳转成功");
            }).catch((err) => {
              console.error("跳转失败", err);
            });
          }else {
            // 自动登陆，跳转到首页
            let ret = await weilaCore.weila_login(
                rsp.data.account.username, 
                rsp.data.account.passwd, 
                rsp.data.account.countrycode,
                WL_ClientType.CLIENT_MINIPROGRAM,
                true);
            
            console.log("微喇登录结果", ret);

            wx.switchTab({
              url: '/pages/life/life-main/life-main'
            }).then(() => {
              console.log("跳转成功");
            }
            ).catch((err) => {
              console.error("跳转失败", err);
            }
            );
            return;
          }

          this.setData({
            isLoaded: false
          }, () => {
            this.startCountdown();
          });
        }else {
          console.error('登录失败', rsp.errmsg);
        }
      }catch (err) {
        console.error('登录失败', err);
      }
    })();
  },

  onUnload(): void {
    // 清理定时器避免内存泄漏
    if (this.timer) {
      clearInterval(this.timer);
    }
  }
});
